package com.slipper.util;

import com.slipper.exception.CommonException;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class MD5 {
    public static String encodePwd(String pwd) {
        if (pwd == null || pwd.isEmpty()) return "";

        for (int i=0; i<3; i++) {
            pwd = encode(i + "_" + pwd + "_" + i);
        }
        return pwd;
    }

    public static String encode(String s) {
        if (s == null || s.isEmpty()) return "";

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] res = md.digest(s.getBytes(StandardCharsets.UTF_8));
            return MD5.dumpBytes(res);
        } catch (Exception e) {
            throw new CommonException("生成MD5摘要出错！", e);
        }
    }

    private static String dumpBytes(byte[] bytes) {
        int size = bytes.length;
        StringBuilder sb = new StringBuilder(size * 2);
        for (byte aByte : bytes) {
            String s = Integer.toHexString(aByte);
            if (s.length() == 8) { // -128 <= bytes[i] < 0
                sb.append(s.substring(6));
            } else if (s.length() == 2) { // 16 <= bytes[i] < 128
                sb.append(s);
            } else {
                sb.append("0").append(s); // 0 <= bytes[i] < 16
            }
        }
        return sb.toString();
    }
}
